import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app_demo/common/event_bus.dart';
import 'package:flutter_app_demo/constants/constants.dart';
import 'package:flutter_app_demo/pages/login_web_page.dart';
import 'package:flutter_app_demo/utils/NetUtils.dart';
import 'package:flutter_app_demo/utils/data_utils.dart';

class ProfilePage extends StatefulWidget {
  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  List menuTitles = [
    '我的消息',
    '阅读记录',
    '我的博客',
    '我的问答',
    '我的活动',
    '我的团队',
    '邀请好友',
  ];
  List menuIcons = [
    Icons.message,
    Icons.print,
    Icons.error,
    Icons.phone,
    Icons.send,
    Icons.people,
    Icons.person,
  ];

  String userAvatar;
  String userName;

  @override
  void initState() {
    super.initState();
    //尝试获取用户信息
    _showUserInfo();

    eventBus.on<LoginEvent>().listen((event) {
      //登录
      //获取用户信息并显示
      _getUserInfo();
    });

    eventBus.on<LogoutEvent>().listen((event) {
      //登出
      _showUserInfo();
    });
  }

  @override
  Widget build(BuildContext context) {
    return ListView.separated(
        itemBuilder: (context, index) {
          if (index == 0) {
            return _buildHeader();
          }
          index = index - 1;
          return ListTile(
            leading: Icon(menuIcons[index]),
            title: Text(menuTitles[index]),
            trailing: Icon(Icons.arrow_forward_ios),
            onTap: () {
              //TODO
            },
          );
        },
        separatorBuilder: (context, index) {
          return Divider();
        },
        itemCount: menuTitles.length + 1);
  }

  Container _buildHeader() {
    return Container(
      height: 150,
      color: Color(AppColors.APP_THEME),
      child: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            GestureDetector(
              child: Container(
                width: 60,
                height: 60,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  border: Border.all(
                    color: Color(0xffffffff),
                    width: 2.0,
                  ),
                  image: DecorationImage(
                    image: userAvatar == null
                        ? AssetImage("images/ycy4.jpg")
                        : NetworkImage(userAvatar),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              onTap: () {
                //执行登录
                _onLogin();
              },
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              userName ??= "点击头像登录",
              style: TextStyle(
                color: Color(0xffffffff),
              ),
            )
          ],
        ),
      ),
    );
  }

  void _showUserInfo() {
    DataUtils.getUserInfo().then((user) {
      if (mounted) {
        setState(() {
          if (user != null) {
            userAvatar = user.avatar;
            userName = user.name;
          } else {
            userAvatar = null;
            userName = null;
          }
        });
      }
    });
  }

  void _onLogin() async {
    var result =
        await Navigator.of(context).push(MaterialPageRoute(builder: (context) {
      return LoginWebPage();
    }));

    print("profile result =$result");
    if (result != null && result == "refresh") {
      //登录成功
      //通知eventbus
      eventBus.fire(LoginEvent());
    }
  }

  void _getUserInfo() {
    DataUtils.getAccessToken().then((token) {
      if (token == null || token.isEmpty) {
        return;
      }
      Map<String, dynamic> params = {
        "access_token": token,
        "dataType": "json",
      };

      NetUtils.get(AppUrls.OPENAPI_USER, params).then((userStr) {
        //个人信息
        //{
        //   "gender": "female",
        //   "name": "osc_64142869",
        //   "location": "广东 深圳",
        //   "id": 5170983,
        //   "avatar": "https://www.oschina.net/img/portrait.gif",
        //   "email": "31e812d7-efa5-4a21-beb5-4aecaa0d4b35",
        //   "url": "https://my.oschina.net/u/5170983"
        // }

        Map<String, dynamic> map = json.decode(userStr);

        if (mounted) {
          setState(() {
            userAvatar = map["avatar"];
            userName = map["name"];
          });
        }
        var user = DataUtils.saveUserInfo(map);
      });
    });
  }
}
